﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using WYJCore;
using WYJCore.Extension;
using WYJData.DatabaseAccess;
using WYJData.Orm;
using WYJWeb.Models;

namespace WYJWeb
{
    public static class ConsoleCenter
    {
        public static List<Menu> Menus;
        public static List<Test> UnitTestResult = new List<Test>();
        public static readonly Type[] Controllers;
        public static readonly Type[] Models;

        static ConsoleCenter()
        {
            var file = File.ReadAllTextAsync(Environment.CurrentDirectory + "/menu.json",Encoding.UTF8).Result;
            Menus = JsonConvert.DeserializeObject<List<Menu>>(file);
            var classes = new Classes().Types;
            Controllers = classes.Where(x => x.Name.EndsWith("Controller")).ToArray();
            Models = classes.Where(x => x.IsModel()).ToArray();
            new Database().AccessDb(command =>
            {
                Models.ForEach(x => new Table(x).CreateDbTable(command));
            });

        }

        public static IApplicationBuilder UseWYJRouter(this IApplicationBuilder application, Action action = null)
        {
            return application.UseMiddleware<WYJRouter>(action);
        }

        public static dynamic TryGetController(string name,out Type controllerType)
        {
            if(GetControllerType(name + "Controller") is Type _controllerType)
            {
                controllerType = _controllerType;
                try
                {
                    dynamic controller = Activator.CreateInstance(controllerType);
                    return  controller;
                }
                catch(Exception e)
                {
                    throw new WYJException($"创建{name}Controller的实例失败:{e.Message}" );
                }
            }
            throw new WYJException($"未找到控制器{name}Controller");
        }

        public static Type GetControllerType(string name)
        {
            return Controllers.FirstOrDefault(x => x.Name.EqualTo(name));
        }

    }
}
